package com.onec.service.design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * jdk 动态代理
 */

public class DynamicLogProxy implements InvocationHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(DynamicLogProxy.class);
  // 需要代理的对象类
  private Object target;

  public DynamicLogProxy(Object target) {
    this.target = target;
  }


  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    LOGGER.info("切入日志");
    Object invoke = method.invoke(target, args);
    LOGGER.info("切入日志:记录结束");
    return invoke;
  }
}

//测试示例
class Test {

  public static void main(String[] args) {

    OrderServiceImpl orderServiceImpl = new OrderServiceImpl();
    Class<?> clazz = orderServiceImpl.getClass();
    DynamicLogProxy dynamicLogProxy = new DynamicLogProxy(orderServiceImpl);

    ////通过Proxy.newProxyInstance(类加载器, 接口s, 事务处理器Handler) 加载动态代理
    OrderService orderService1 = (OrderService) Proxy
        .newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), dynamicLogProxy);

    orderService1.createOrder();
  }
}
